package at.bubblebird.todoapp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.*;

import android.os.AsyncTask;

public class LoadTodosAsyncTask extends AsyncTask<URL, Boolean, Boolean> {

	private ArrayList<String> todos;
	
	@Override
	protected Boolean doInBackground(URL... arg0) {
		
		try {
		    URL url = arg0[0];

		    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
		    String str;
		    StringBuffer srb = new StringBuffer();
		    while ((str = in.readLine()) != null) {
		       srb.append(str);
		    }
		    in.close();
		    
		    JSONObject jObj = new JSONObject(srb.toString());
		    
		    todos = new ArrayList<String>();
		    
		    if(!jObj.getBoolean("iE")){
		    	
		    	JSONArray ja = jObj.getJSONArray("todos");
		    	
		    	for(int c = 0; c < ja.length(); c++){
		    		todos.add(ja.getJSONObject(c).getString("title"));
		    	}
		    	
		    	return true;
		    }
		    else return false;
		    
		} catch (Exception e) {e.printStackTrace();}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		if(result) TodoActivity.instance.setTodos(todos);
    }

}
